package com.spzx.product.helper;

import com.spzx.product.api.domain.vo.CategoryVo;
import com.spzx.product.domain.Category;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

public class CategoryHelper {
    public static List<CategoryVo> buildTree(List<CategoryVo> categoryVoList){
        List<CategoryVo> oneCategoryVoList=new ArrayList<>();
        if (!CollectionUtils.isEmpty(categoryVoList)){
            for (CategoryVo vo : categoryVoList) {

                if (vo.getParentId()==0){
                    vo=findChildren(vo,categoryVoList);
                    oneCategoryVoList.add(vo);
                }
            }
        }
        return oneCategoryVoList;
    }
    /**
     * 递归：找孩子
     *
     * @param vo 当前分类
     * @param categoryVoList 所有分类
     * @return 当前分类（children属性装满孩子）
     */
    private static CategoryVo findChildren(CategoryVo vo, List<CategoryVo> categoryVoList) {
        vo.setChildren(new ArrayList<>());   //孩子集合初始化
        for (CategoryVo categoryVo : categoryVoList) {
            if (vo.getId().intValue()==categoryVo.getParentId().intValue()){ //找孩子
                categoryVo=findChildren(categoryVo,categoryVoList);   //孩子找孩子
                vo.getChildren().add(categoryVo);
            }
        }
        return vo;
    }
}
